package metrics

import (
	"encoding/json"
	"fmt"
	"os"
	"path"
	"strings"

	"gopkg.openfuyao.cn/bkecommon/utils"
)

const (
	e2eDataSavePath = "/bke2e/metrics"
)

func (r *BKEClusterMetricRegister) E2EDataGather(key string) error {
	if !utils.Exists(e2eDataSavePath) {
		if err := os.MkdirAll(e2eDataSavePath, 0755); err != nil {
			return err
		}
	}

	metricsGather, err := r.Gather(key, PhaseDurationSeconds, NodeBootstrapDurationSeconds)
	if err != nil {
		return err
	}

	resp := make([]httpExportResponse, 0)
	for name, metrics := range metricsGather {
		switch name {
		case PhaseDurationSeconds:
			for _, metric := range metrics {
				respItem := httpExportResponse{
					Name:      metric["phase"],
					StartTime: metric["start_time"],
					EndTime:   metric["end_time"],
					Describe:  metric["describe"],
					Duration:  calculateTimeDifference(metric["start_time"], metric["end_time"]),
				}
				resp = append(resp, respItem)
			}
		case NodeBootstrapDurationSeconds:
			//[]string{"node", "role", "boot_success", "start_time", "end_time"},
			for _, metric := range metrics {
				respItem := httpExportResponse{
					Name:      metric["node"],
					StartTime: metric["start_time"],
					EndTime:   metric["end_time"],
					Describe:  fmt.Sprintf("node: %s, bootstrap success: %s", metric["node"], metric["boot_success"]),
					Duration:  calculateTimeDifference(metric["start_time"], metric["end_time"]),
				}
				resp = append(resp, respItem)
			}
		default:

		}
	}

	metricsData, err := json.MarshalIndent(resp, "", " ")
	if err != nil {
		return err
	}
	key = strings.Replace(key, "/", "_", -1)

	metricsPath := fmt.Sprintf("%s/%s.json", e2eDataSavePath, key)
	if !utils.Exists(path.Dir(metricsPath)) {
		if err := os.MkdirAll(path.Dir(metricsPath), 0755); err != nil {
			return err
		}
	}

	if err := os.WriteFile(metricsPath, metricsData, 0644); err != nil {
		return err
	}

	return nil
}
